<?php
/**
 * Created by PhpStorm.
 * User: CTDJ1803111
 * Date: 2018/12/11
 * Time: 15:39
 */

namespace app\common\middleware;

use app\common\facade\JWT;
use traits\ResponsDataBuild;
use \Firebase\JWT\ExpiredException;
use  \Exception;

class TokenCheck
{
    use ResponsDataBuild;

    public function handle($request, \Closure $next)
    {
        $token = $request->header('token');
        if (empty($token)) {
            return $this->returnError(22);
        }
        try {
            $data = JWT::decode($token);
            isset($data->id) && $request->id = $data->id;
            isset($data->member_id) && $request->member_id = $data->member_id;
            isset($data->id) && session('admin_user_id', $data->id);
            isset($data->member_id) && session('member_id', $data->member_id);
        } catch (ExpiredException $ex) {
            return $this->returnError(24);
        } catch (Exception $ex) {
            return $this->returnError(2, [], $ex->getMessage());
        }
        return $next($request);
    }
}
